package com.bright.cwduijie.duijie.web.controller;

import com.bright.cwduijie.common.util.RestResult;
import com.bright.cwduijie.common.util.StringUtil;
import com.bright.cwduijie.duijie.constant.ConfigConstants;
import com.bright.cwduijie.duijie.enums.DataApi;
import com.bright.cwduijie.duijie.enums.SJJHBZ;
import com.bright.cwduijie.duijie.pojo.command.*;
import com.bright.cwduijie.duijie.pojo.dto.QueryTaskDto;
import com.bright.cwduijie.duijie.pojo.dto.QueryTaskReturnDto;
import com.bright.cwduijie.duijie.service.DuijieService;
import com.bright.cwduijie.duijie.service.WebExchangeService;
import com.bright.cwduijie.duijie.task.TimedTask;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;

/**
 * @Author hxj
 * @Date 2024/7/4 15:18
 * @Description
 */

@RequestMapping("/duijie")
@Controller
@RequiredArgsConstructor
@RestController
@Slf4j
public class DuijieController {

    private final ConfigConstants constants;

    private final DuijieService duijieService;

    @Qualifier("normal")
    private final WebExchangeService webExchangeService;

    private final TimedTask timedTask;


    @RequestMapping("/start")
    public RestResult start(@Valid DuijieCommand command) {
        printPublicKeys();
//        String[] buildAccSets = getAccSetList(accSets);
//        try {
//            duijieService.duijie(new DuijieCommand(years, months, buildAccSets));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//
//        return RestResult.success();

        return startNoBatch(command);
    }

    private void printPublicKeys() {
        log.debug("网址=[" + constants.getDomain() + constants.getRootPath() + "]");
        log.debug("appId=[" + constants.getAppId() + "]");
        log.debug("appSecret=[" + constants.getAppSecret() + "]");
        log.debug("appSecretIV=[" + constants.getAppSecretIV() + "]");
        log.debug("appPrivateKey=[" + constants.getAppPrivateKey() + "]");
        log.debug("appPublicKey=[" + constants.getAppPublicKey() + "]");
        log.debug("jtzcPublicKey=[" + constants.getJtzcPublicKey() + "]");

    }

    /**
     * 调用存储过程生成数据
     * @return
     */
    @RequestMapping("/buildAndStart")
    public RestResult buildAndStart(@RequestParam Integer years, @RequestParam Integer months,
                                    @RequestParam(required = false) List<Object> accSets, @RequestParam(required = false) List<Integer> accModal) {
        printPublicKeys();
        BuildCommand buildCommand = new BuildCommand(years, months, accSets, accModal);
        DuijieCommand duijieCommand = new DuijieCommand(years, months, accSets);

        try {
            duijieService.buildOneAndStartOne(buildCommand, duijieCommand);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return RestResult.success();
    }

    @RequestMapping("/build")
    public RestResult build(@RequestParam Integer years, @RequestParam Integer months,
                            @RequestParam(required = false) List<Object> accSets, @RequestParam(required = false) List<Integer> accModal) {
        duijieService.build(new BuildCommand(years, months, accSets, accModal));
        return RestResult.success();
    }

    @RequestMapping("/dataKey/delete")
    public RestResult deleteDataKeys(@RequestParam String serviceCode) {
        try {
            duijieService.deleteDataKeys(serviceCode);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return RestResult.success();
    }

    @RequestMapping("/queryTask")
    public RestResult queryTask() {
        duijieService.checkAsyncTasks();

        return RestResult.success();
    }


    /**
     * 根据taskId 查询结果
     * @return
     */
    @RequestMapping("/queryTaskFromTaskId")
    public RestResult queryTaskFromTaskId(@RequestParam("taskIds") List<String> taskIds) {

        QueryTaskDto queryTaskDto = new QueryTaskDto(taskIds);
        List<QueryTaskReturnDto> queryTaskReturnDtos = webExchangeService.queryTask(queryTaskDto);
        if (queryTaskReturnDtos == null) {
            return RestResult.fail("查询出错，请查看日志！");
        }

        return RestResult.success(queryTaskReturnDtos);
    }

    @RequestMapping("/noBatch/start")
    public RestResult startNoBatch(@Valid DuijieCommand duijieCommand) {
        try {
            String successMessage = duijieService.startByOnlyOneBatch(duijieCommand);
            return RestResult.success(successMessage);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (RuntimeException e) {
            log.error("出现异常：", e);
            return RestResult.fail("出现异常：" + e.getMessage());
        }


//        return RestResult.success();
    }

    // 保留原来分批次推送的接口
    @RequestMapping("/batch/start")
    public RestResult startWithBatch(@Valid DuijieCommand command) {
        printPublicKeys();
        try {
            duijieService.duijie(command);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return RestResult.success();
    }

    @RequestMapping("/test")
    public RestResult test(@RequestParam(required = false) List<Object> accSets, @RequestParam(required = false) List<Integer> accModals) {

        return RestResult.success(accModals);
    }

    @RequestMapping("/startSendFile")
    public RestResult startSendFile() {
        try {
//            duijieService.sendFiles();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return RestResult.success();
    }


    @RequestMapping("/startRemoveFile")
    public RestResult startRemoveFile() {
        try {
//            duijieService.deleteFiles();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return RestResult.success();
    }

    @RequestMapping("/sendDefaultVoucherEntry")
    public RestResult sendDefaultVoucherEntry(SendDefaultVoucherEntryCommand command) {
        try {
            duijieService.sendVoucherWithDefaultVoucherEntry(Collections.singletonList(command));
        } catch (Exception e) {
            log.error("", e);
            return RestResult.fail("异常：" + e.getMessage());
        }

        return RestResult.success();
    }

    @RequestMapping("/updateSjjhbzByIds")
    public RestResult updateSjjhbzByIds(@RequestParam Integer opType, @RequestParam String serviceCode, @RequestParam List<Integer> ids) {
        Optional<DataApi> optionalDataApi = DataApi.ofOptional(serviceCode);
        if (!optionalDataApi.isPresent()) {
            return RestResult.fail("serviceCode=" + serviceCode + " 不存在");
        }
        DataApi dataApi = optionalDataApi.get();
        UpdateOpTypeSjjhbzCommand command = new UpdateOpTypeSjjhbzCommand();
        command.setIds(ids);
        command.setSjjhbz(SJJHBZ.WAITING.getValue());
        command.setOpType(opType);
        try {
            duijieService.updateSjjhbzByServiceCodeAndIds(command, dataApi);
        } catch (Throwable throwable) {
            log.error("", throwable);
            return RestResult.fail("执行出错：" + throwable.getMessage());
        }
        return RestResult.success();
    }

    @RequestMapping("/processVoucherError")
    public RestResult processVoucherError(ProcessVoucherErrorCommand command) {
        try {
            duijieService.processVoucherError(command);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return RestResult.success();
    }

    @RequestMapping("/pushMonthDataByBatch")
    public RestResult pushMonthDataByBatch(@Valid PushMonthDataByBatchCommand command) {
        try {
            duijieService.pushMonthDataOrderByMonthByBatch(command);
        } catch (Throwable throwable) {
            log.error("", throwable);
            return RestResult.fail("执行出错：" + throwable.getMessage());
        }
        return RestResult.success();
    }

    @RequestMapping("/processFixedAssetsError")
    public RestResult processFixedAssetsError() {
        // v1.6.12 改成手动调用
        duijieService.autoProcessFixedAssetsError();
        return RestResult.success();
    }



}
